import { login, logout, getInfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    token: getToken() || null,
    userInfo: null
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  removeUserInfo(state) {
    state.userInfo = null
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  SET_USERINFO: (state, data) => {
    state.userInfo = data
  }
}

const actions = {
  // user login
  login(context, userInfo) {
    const { mobile, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ mobile: mobile, password: password }).then((response) => {
        Message({
          message: response.message || 'Error',
          type: 'success',
          duration: 5 * 1000
        })
        const { data } = response
        context.commit('SET_TOKEN', data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(async response => {
        const { data } = response
        const info = await getUserDetailById(data.userId)
        commit('SET_USERINFO', { ...info.data, ...data })
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

  // data表示接口参数
  async userLogin(context, obj) {
    // 调用ajax请求去做登陆
    const res = await login(obj)
    // 在actions中，如果要修改state，还是要调用mutaions
    // context.commit('mutation名'， 参数)
    context.commit('SET_TOKEN', res.data)
  },

  userLogout(context) {
    context.commit('removeUserInfo')
    context.commit('removeToken')
    // 重置路由
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

